package com.lordtan.commom.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 对象操作工具
 * @author lordtan
 * @date 2012-12-9
 */
public class ObjectUtils {
    /**
     * 将map中的数据写入bean中
     * @param map
     * @param bean
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
	public static void mapToBean(Map<String,Object> map, Object bean) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		if(null==map || null==bean){
			return ;
		}
		Class<? extends Object> claz = bean.getClass();
		Method [] methods = claz.getMethods();
		Set<String> keys = map.keySet();
		Iterator<String> it  = keys.iterator();
		while(it.hasNext()){
			String key = it.next();
			for(Method method : methods){
				String methodName = method.getName();
				if(methodName.equals("set"+key.substring(0,1).toUpperCase()+key.substring(1))){
					Object value = map.get(key);
					method.invoke(bean, value);
					continue;
				}
			}
		}
	}
	
	/**
	 * 将bean中的数据写入map中
	 * @param bean
	 * @param map
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public static void beanToMap(Object bean, Map<String,Object> map) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		if(null==map || null==bean){
			return ;
		}
		Class<? extends Object> claz = bean.getClass();
		Field [] fields = claz.getFields();
		Method [] methods = claz.getMethods();
		for(Method method : methods){
			String methodName = method.getName();
			for(Field field : fields){
				String fieldName = field.getName();
				if(methodName.equals("get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1))){
					Object value = method.invoke(bean,new Object []{});
					map.put(fieldName, value);
					continue;
				}
			}
		}
	}
}

